/**
 *
 */
package com.ruicar.afs.cloud.easypass.process.service.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.ruicar.afs.cloud.common.core.enums.AfsEnumUtil;
import com.ruicar.afs.cloud.common.core.uid.UidGenerator;
import com.ruicar.afs.cloud.easypass.entity.BasicMainEasypassLogs;
import com.ruicar.afs.cloud.easypass.enums.RequestEasypassPathEnum;
import com.ruicar.afs.cloud.easypass.enums.RsponseStatusEnum;
import com.ruicar.afs.cloud.easypass.process.config.EasypassConfig;
import com.ruicar.afs.cloud.easypass.process.dto.*;
import com.ruicar.afs.cloud.easypass.process.dto.SmsVerifyDTO.SmsVerifyRspDTO;
import com.ruicar.afs.cloud.easypass.process.feign.EasypassProcessFeign;
import com.ruicar.afs.cloud.easypass.process.service.IEasypassProcessService;
import com.ruicar.afs.cloud.easypass.service.BasicMainEasypassLogsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.Date;

/**
 *<p>Description: </p>  
 * @author happysayhello
 * @date Jul 26, 2020 
 */
@Slf4j
@Service
public class EasypassProcessServiceImpl implements IEasypassProcessService {

    @Autowired
    private BasicMainEasypassLogsService logsService;

    @Autowired
    private EasypassProcessFeign easypassProcessFeign;

    @Autowired
    private UidGenerator uidGenerator;

    @Autowired
    private EasypassConfig config;

    @Override
    public <T> EasypassRsponseBean<T> commonSendProcess(RequestEasypassPathEnum pathEnum,
                                                        EasypassRequestBean requestBean, Class<T> resClass) {
        // TODO Auto-generated method stub
        return null;
    }
    /**
     * 代付批量
     */
    @Override
    public EasypassRsponseBean payBatchApply(PayBatchApplyDTO dto,String msgid) {
        EasypassRsponseBean respBean = null;
        BasicMainEasypassLogs logs = null;
        EasypassRequestBean<PayBatchApplyDTO> requestBean = null;
        try {
            requestBean = new EasypassRequestBean<PayBatchApplyDTO>();
            requestBean.setBody(dto);
            String reqtime = DateUtil.format(DateUtil.date(), DatePattern.PURE_DATETIME_PATTERN);
            requestBean.setMsgid(msgid);
            requestBean.setOpenid(config.getOpenid());
            requestBean.setReqtime(reqtime);
            requestBean.setAppid(config.getAppid());
            requestBean.setChlCd(dto.getData().get(0).getChlCd());
            String msg = JSON.toJSONString(requestBean);
            logs = saveLogs(requestBean, RequestEasypassPathEnum.PAY_APPLY_BATCH);
            String rspMsg = easypassProcessFeign.payBatchApply(msg);
            respBean = JSONObject.parseObject(rspMsg, EasypassRsponseBean.class);
        } catch (Exception e) {
            log.error("发送睿易通错误", e);
            if (ObjectUtils.isEmpty(respBean)) {
                exceptionRsponseBean(requestBean, e);
            }

        } finally {
            updateLogs(respBean, logs);
        }

        return respBean;
    }
    /**
     * 代扣批量
     */
    @Override
    public EasypassRsponseBean recBatchApply(RecBatchApplyDTO dto) {

        EasypassRsponseBean respBean = null;
        BasicMainEasypassLogs logs = null;
        EasypassRequestBean<RecBatchApplyDTO> requestBean = null;
        try {
            requestBean = new EasypassRequestBean<RecBatchApplyDTO>();
            initHeader(requestBean);
            requestBean.setBody(dto);
            String msg = JSON.toJSONString(requestBean);
            logs = saveLogs(requestBean, RequestEasypassPathEnum.PAY_APP_BATCH);
            String rspMsg = easypassProcessFeign.recBatchApply(msg);
            respBean = JSONObject.parseObject(rspMsg, EasypassRsponseBean.class);
        } catch (Exception e) {
            log.error("发送睿易通错误", e);
            if (ObjectUtils.isEmpty(respBean)) {
                exceptionRsponseBean(requestBean, e);
            }

        } finally {
            updateLogs(respBean, logs);
        }

        return respBean;
    }

    @Override
    public EasypassRsponseBean<PayResultQryDTO> payResultQry(String msgid) {

        EasypassRequestBean requestBean = new EasypassRequestBean();
        EasypassRsponseBean<PayResultQryDTO> rspBean = null;
        try {
            initHeader(requestBean);
            requestBean.setBody(EasyPassQryBean.builder().serialNo(msgid).build());
            String msg = JSON.toJSONString(requestBean);
            log.info("查询睿易通付款结果"+msg);
            String rspMsg = easypassProcessFeign.payBatchQry(msg);
            log.info("睿易通返回报文"+rspMsg);
            rspBean = JSONObject.parseObject(rspMsg, new TypeReference<EasypassRsponseBean<PayResultQryDTO>>() {
            });

        } catch (Exception e) {
            log.error("查询回盘结果失败", e);
            exceptionRsponseBean(requestBean, e);
        }
        return rspBean;
    }

    @Override
    public EasypassRsponseBean<RecResultQryDTO> recResultQry(String msgid) {
        EasypassRequestBean requestBean = new EasypassRequestBean();
        EasypassRsponseBean<RecResultQryDTO> rspBean = null;
        try {
            initHeader(requestBean);
            requestBean.setBody(EasyPassQryBean.builder().serialNo(msgid).build());

            String msg = JSON.toJSONString(requestBean);
            log.info("查询睿易通扣款结果"+msg);
            String rspMsg = easypassProcessFeign.recBatchQry(msg);
            log.info("睿易通返回报文"+rspMsg);
            rspBean = JSONObject.parseObject(rspMsg, new TypeReference<EasypassRsponseBean<RecResultQryDTO>>() {
            });

        } catch (Exception e) {
            log.error("回盘结果失败", e);
            exceptionRsponseBean(requestBean, e);
        }
        return rspBean;
    }

    //签约获取验证码
    @Override
    public EasypassRsponseBean<SmsVerifyRspDTO> sendSmsVerify(SmsVerifyDTO dto) {
        EasypassRsponseBean<SmsVerifyRspDTO> respBean = null;
        BasicMainEasypassLogs logs = null;
        EasypassRequestBean<SmsVerifyDTO> requestBean = new EasypassRequestBean<SmsVerifyDTO>();
        try {
            initHeader(requestBean);
            requestBean.setBody(dto);
            String msg = JSON.toJSONString(requestBean);
            logs = saveLogs(requestBean, RequestEasypassPathEnum.SMS_VERIFY);
            String rspMsg = easypassProcessFeign.sendSmsVerify(msg);
            respBean = JSONObject.parseObject(rspMsg, new TypeReference<EasypassRsponseBean<SmsVerifyRspDTO>>() {
            });
        } catch (Exception e) {
            log.error("发送睿易通错误", e);
            if (ObjectUtils.isEmpty(respBean)) {
                exceptionRsponseBean(requestBean, e);
            }

        } finally {
            updateLogs(respBean, logs);
        }

        return respBean;
    }

    /**
     * 初始化报文头
     * @param bean
     */
    public void initHeader(EasypassRequestBean bean) {
        String msgid = StringUtils.rightPad(String.valueOf(uidGenerator.getUID()), 32, "0");
        String reqtime = DateUtil.format(DateUtil.date(), DatePattern.PURE_DATETIME_PATTERN);
        bean.setMsgid(msgid);
        bean.setOpenid(config.getOpenid());
        bean.setReqtime(reqtime);
        bean.setAppid(config.getAppid());
    }

    public BasicMainEasypassLogs saveLogs(EasypassRequestBean requestBean, RequestEasypassPathEnum path) {

        BasicMainEasypassLogs logs = new BasicMainEasypassLogs();
        logs.setMsgId(requestBean.getMsgid());
        logs.setReqCd(AfsEnumUtil.key(path));
        logs.setReqMsg(JSON.toJSONString(requestBean));
        logs .setReqPath(AfsEnumUtil.key(path));
        logs .setReqTime(DateUtil.date());
        logsService.save(logs);
        return logs;
    }

    public void updateLogs(EasypassRsponseBean rspBean, BasicMainEasypassLogs log) {

        log.setRspCode(rspBean.getResultCode());
        log.setRspErrMsg(rspBean.getResultDesc());
        log.setRspTime(new Date(Long.valueOf(rspBean.getRsptime())));
        log.setRspMsg(JSON.toJSONString(rspBean));
        logsService.saveOrUpdate(log);
    }

    public EasypassRsponseBean exceptionRsponseBean(EasypassRequestBean reqBean, Exception e) {
        EasypassRsponseBean rspBean = new EasypassRsponseBean();
        rspBean.setMsgid(reqBean.getMsgid());
        rspBean.setResultCode(AfsEnumUtil.key(RsponseStatusEnum.INNER_ERROR));
        rspBean.setResultDesc("执行错误:" + StringUtils.left(e.getMessage(), 128));
        rspBean.setRsptime(DateUtil.now());
        return rspBean;
    }

    /**
     * 发送短信内容或者验证码进行签约确定
     */
    @Override
    public EasypassRsponseBean sendSignApply(SmsSignApplyDTO dto) {
        EasypassRsponseBean respBean = null;
        BasicMainEasypassLogs logs = null;
        EasypassRequestBean<SmsSignApplyDTO> requestBean = new EasypassRequestBean<SmsSignApplyDTO>();
        try {
            initHeader(requestBean);
            requestBean.setBody(dto);
            String msg = JSON.toJSONString(requestBean);
            logs = saveLogs(requestBean, RequestEasypassPathEnum.PAY_SIGN);
            String rspMsg = easypassProcessFeign.sendSmsVerify(msg);
            respBean = JSONObject.parseObject(rspMsg, new TypeReference<EasypassRsponseBean>() {
            });
        } catch (Exception e) {
            log.error("发送睿易通错误", e);
            if (ObjectUtils.isEmpty(respBean)) {
                exceptionRsponseBean(requestBean, e);
            }

        } finally {
            updateLogs(respBean, logs);
        }

        return respBean;
    }
}
